package org.vectrics.common.tree;


import java.util.*;
import org.apache.log4j.*;

class TreeImpl implements Tree, java.io.Serializable {
	private transient static Logger log = Logger.getLogger(TreeImpl.class);
    private HashSet masterList = null;
    private TreeNode root = null;

    public TreeImpl() {
    }

    
    public HashSet getMasterList()
    {
        if (masterList == null)
            masterList = new HashSet();
        return(masterList);
    };
    
    public void remove(TreeNode node) {
        TreeNode nodeDelete = find(node.getId());
        if (nodeDelete != null) {
            getMasterList().remove(nodeDelete);
            TreeNode rootNode = getRoot();
            if (rootNode != null) {
                rootNode.remove(nodeDelete, true);
            }
        }
    }
    
    public TreeNode find(String id) {
    	if (log.isDebugEnabled())
    		log.debug("find(id) - called, id = " + id);
    	Iterator iter = getMasterList().iterator();
        TreeNode found = null;
        if (id != null) {
            while ((found == null) && (iter.hasNext())) {
                TreeNode node = (TreeNode)iter.next();
                String nodeId = node.getId();
                
                if (log.isDebugEnabled())
                	log.debug("find(id) - looking at node with id = " + nodeId);
                
                if (nodeId != null) {
                	if (nodeId.compareTo(id.trim()) == 0) {
	                    found = node;
	                    log.debug("find(id) - node id matches required id, done");
                	}
                	else {
                		log.debug("find(id) - node id doesn't match required id");
                	}
                }
                else {
                	log.debug("id of node was null");
                }
            }
        }
        
        return(found);
    }

    public int size() {
        return(getMasterList().size());
    }
    
    public TreeNode getRoot() {
        return(root);
    }

    public void setRoot(TreeNode root) {
    	log.debug("setRoot(node) called");
    	this.root = root;
        getMasterList().add(root);
    };

    
    public String getHierarchy() {
        String str = "NO ROOT DEFINED";
        if (root != null)
            str = root.getHierarchy();
        return(str);
    }
    
    

}